// \u4e00-\u9fa5] 中文验证规则

Page({
  data: {
    point: '',
    building: '',
    room: 0,
    name: '',
    gender: 1,
    mobile: '',
    idcardFrontUrl: '/static/images/avatar_1.jpg',
    idcardBackUrl: '/static/images/avatar_2.jpg',
  },
  onLoad(params) {
    const {
      point,
      building,
      room,
      id
    } = params
    if (id) {
      // 设置标题
      wx.setNavigationBarTitle({
        title: '编辑房屋信息',
      })
      // 根据 ID 获取详情
      this.getHouseDetail(id)
    } else {
      this.setData({
        point: decodeURIComponent(point),
        building: decodeURIComponent(building),
        room: room
      })
    }
  },
  async getHouseDetail(id) {
    const {
      code,
      data
    } = await wx.http.get(`/room/${id}`)
    if (code !== 10000) return wx.utils.toast()
    this.setData(data)
  },
  goList() {
    wx.reLaunch({
      url: '/house_pkg/pages/list/index',
    })
  },
  removePicture(ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark?.type
    this.setData({
      [type]: ''
    })
  },
  async uploadPicture(e) {
    try {
      const r = await wx.chooseMedia({
        count: 1, // 只能选择1张图片
        mediaType: ['image'], // 只能选择图片类型
        sizeType: ['compressed'], // 默认为压缩模式
      })
      // console.log(r)
      // 用 wx.uploadFile 可以把 res.tempFiles[0].tempFilePath 存到后端
      wx.uploadFile({
        url: wx.http.baseURL + '/upload',
        filePath: r.tempFiles[0].tempFilePath,
        name: 'file',
        formData: {
          type: 'avatar'
        },
        header: {
          Authorization: getApp().token
        },
        success: ({
          data
        }) => {
          const dataRes = JSON.parse(data)
          this.setData({
            [e.mark.type]: dataRes.data.url
          })
        },
        fail() {}
      })
    } catch (e) {
      console.log(e)
    }
  },
  verifyName() {
    const reg = /^[\u4e00-\u9fa5]{2,5}$/
    return reg.test(this.data.name.trim())
  },
  verifyMobile() {
    const reg = /^[1][3-8]\d{9}$/
    return reg.test(this.data.mobile.trim())
  },
  verifyPicture() {
    const {
      idcardFrontUrl,
      idcardBackUrl
    } = this.data
    const isValid = !!idcardFrontUrl && !!idcardBackUrl
    return isValid

  },
  async submitForm() {
    if (!this.verifyName()) return wx.utils.toast('请输入合法的姓名')
    if (!this.verifyMobile()) return wx.utils.toast('请输入合法的手机号码')
    if (!this.verifyPicture()) return wx.utils.toast('请选择身份证')

    delete this.data.__webviewId__
    // 获取详情的时候，后端返回的有一个 status，但调用编辑接口的时候，后端并不需要，所以删了
    delete this.data.status

    const r = await wx.http.post('/room', this.data)
    if (r.code !== 10000) return wx.utils.toast()
    wx.navigateBack({
      delta: this.data.id ? 2 : 4
    })
  }
})